import { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { SearchBar } from 'antd-mobile';
import cls from 'classnames';
import { InbizIcon, extendApi, useEvents, NavigationBack } from '@inbiz/utils';
import { getMessage } from '@inbiz/react';
import Content from './components/Content';
import { TabsConfigState } from '../../store/searchPropsContext';
import { SearchEngineProps } from '../web';
import './style.less';

export interface ISearchWapProps {
  viewType: string;
  wapviewType: string,
  title: {
    status: boolean;
    value: string;
  };
  indexRange: boolean;
  hotKeywordsNumber: number;
  searchResultComponent: string;
  searchResultType: string;
  searchResultPage: string;
  hotKeywordsSwitch: boolean;
  emit: (type: string, searchResultComponent: any, params: any) => void;
  tabsConfig: TabsConfigState[];
  callBackEvents: SearchEngineProps['callBackEvents'];
  searchResultPageType: '_self' | '_blank';
  inbiz: any;
  placeholder: string;
  icon: {
    color: string;
    type: string;
  };
  historySearch: boolean,
  synonymSearch: boolean,
  rangeType?: 'pull' | 'popup'
}

const prefixCls = 'inbiz-search-engine-wap';
const Search = forwardRef((props: ISearchWapProps, ref) => {
  const {
    viewType,
    wapviewType,
    title,
    indexRange,
    hotKeywordsNumber,
    searchResultComponent,
    searchResultType,
    searchResultPage,
    hotKeywordsSwitch,
    icon,
    emit,
    placeholder,
    inbiz,
    historySearch,
    synonymSearch,
    rangeType
  } = props;

  const [configEvents] = useEvents(props.callBackEvents);

  const searchResult = {
    searchResultComponent,
    searchResultType,
    searchResultPage,
  };
  const storage = useMemo(() => {
    const data = localStorage.getItem(`_searchEngineStatus`) || sessionStorage.getItem(`_searchEngineStatus`);
    if (data) {
      try {
        return JSON.parse(data)
      } catch (error) {
        return {}
      }
    }
  }, []);
  const [visible, setVisible] = useState<boolean>(false);
  const [searchValue, setSearchValue] = useState<string>(() => storage?.KeyWord || '');
  const searchClick = () => {
    setVisible(true);
  };
  const tabsConfig = useMemo(() => {
    return props.tabsConfig.filter((item) => item.isShow !== false);
  }, [props.tabsConfig]);
  const renderContent = useMemo(() => {
    if (wapviewType === 'inlineView') {
      return (
        <div className={cls(`${prefixCls}-icon`)} onClick={searchClick}>
          <InbizIcon
            type={icon?.type || 'icon-mokuai-tongyisousuoyinqing'}
            style={{ color: icon.color }}
          />
        </div>
      );
    } else {
      return (
        <div className={cls(`${prefixCls}`)} onClick={searchClick}>
          <SearchBar
            value={searchValue}
            placeholder={getMessage(placeholder || 'SearchEngine.enterSearchContent')}
            className="custom-search-bar"
            clearable={false}
            icon={icon?.type ? <InbizIcon type={icon?.type} style={{ color: icon.color }} /> : null}
            style={{ pointerEvents: 'none' }} // 只用于显示，解决ios下 光标异常问题
          />
        </div>
      );
    }
  }, [viewType, searchValue, icon, placeholder, wapviewType]);
  // 初始化搜索入口的值
  const initSearchValue = (_searchId: string, resultId: string, data: any = {}) => {
    const { KeyWord } = data;
    if (searchValue != '' && KeyWord) {
      setSearchValue(KeyWord);
    }
  };
  useEffect(() => {
    // if (storage) {
    //   const result = JSON.parse(storage);
    //   setSearchValue(result?.KeyWord || '');
    // }
    if (inbiz.browser.designer) {
      return;
    }
    // 搜索组件在页面内
    inbiz?.on?.('searchData._param', initSearchValue);
    // 搜索组件在全局布局中
    inbiz.global?.on?.('searchData._param', initSearchValue);
    return () => {
      if (inbiz.browser.designer) {
        return;
      }
      inbiz?.off?.('searchData._param');
      inbiz.global?.off?.('searchData._param');
    };
  }, [storage]);
  const clearStorage = () => {
    setSearchValue('')
    localStorage.removeItem('_searchEngineStatus')
    sessionStorage.removeItem('_searchEngineStatus')
  }
  useImperativeHandle(ref, () => extendApi(() => ({
    clearSearchInput: clearStorage
  }))(configEvents), [storage]);
  // 默认模糊搜索, 优先取缓存中的值
  // 没有缓存,,默认模糊搜索, 有缓存,如果isFuzzySearch是true,则是模糊搜索
  const [searchType, setSearchType] = useState<'accurateSearch' | 'vagueSearch'>(!storage ? 'vagueSearch' : storage.isFuzzySearch ? 'vagueSearch' : 'accurateSearch');
  const [tagConfig, setTagConfig] = useState<TabsConfigState>(() => {
    if (storage?.ModuleName) {
      return tabsConfig.find(item => item.guid === storage?.ModuleName) || tabsConfig[0]
    } else {
      return tabsConfig[0]
    }
  }); // 当前选择的标签配置

  return (
    <div>
      {renderContent}
      <NavigationBack visible={visible}>
        {createPortal(
          <Content
            searchType={searchType}
            setSearchType={setSearchType}
            tagConfig={tagConfig}
            setTagConfig={setTagConfig}
            title={title}
            indexRange={indexRange}
            tabsConfig={tabsConfig}
            searchResult={searchResult}
            hotKeywordsNumber={hotKeywordsNumber}
            emit={emit}
            setVisible={setVisible}
            setSearchValue={setSearchValue}
            hotKeywordsSwitch={hotKeywordsSwitch}
            configEvents={configEvents}
            searchResultPageType={props.searchResultPageType}
            inbiz={props.inbiz}
            placeholder={placeholder || 'SearchEngine.enterSearchContent'}
            icon={icon}
            historySearch={historySearch}
            IsSynonymSearch={synonymSearch}
            rangeType={rangeType}
            searchValue={searchValue}
            clearStorage={clearStorage}
          />,
          document.body,
        )}
      </NavigationBack>
    </div>
  );
});

export default Search;
